package com.stud.postgres.jdbc;

import com.google.common.collect.Lists;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.*;
import java.util.List;

public class ListLongTypeHandler extends BaseTypeHandler<List<Long>> {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, List<Long> longs, JdbcType jdbcType) throws SQLException {
        if (longs != null) {
            Array array = preparedStatement.getConnection().createArrayOf(JdbcType.BIGINT.name(), longs.toArray(new Long[0]));
            preparedStatement.setArray(i, array);
        }
    }

    @Override
    public List<Long> getNullableResult(ResultSet resultSet, String s) throws SQLException {
        Array array = resultSet.getArray(s);
        if (array == null) {
            return null;
        }
        Long[] result = (Long[]) array.getArray();
        array.free();
        return Lists.newArrayList(result);
    }

    @Override
    public List<Long> getNullableResult(ResultSet resultSet, int i) throws SQLException {
        Array array = resultSet.getArray(i);
        if (array == null) {
            return null;
        }
        Long[] result = (Long[]) array.getArray();
        array.free();
        return Lists.newArrayList(result);
    }

    @Override
    public List<Long> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        Array array = callableStatement.getArray(i);
        if (array == null) {
            return null;
        }
        Long[] result = (Long[]) array.getArray();
        array.free();
        return Lists.newArrayList(result);
    }
}

